package com.findviewbydream.evil.helloyouth.View.Dialog.LoadingDialog;

import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.findviewbydream.evil.helloyouth.R;
import com.mmga.metroloading.MetroLoadingView;

/********************************************
 * 工程名：HelloYouth
 * 包名：com.findviewbydream.evil.helloyouth.Utils.Dialog.LoadingDialog
 * 时间：16-6-11 上午12:23
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：
 ********************************************/
public class LoadingDialog extends Dialog
{
    private static MetroLoadingView loadingView;
    private static boolean canBeBack = true;
    private static CallBack callBack;


    public LoadingDialog(Context context, int themeResId)
    {
        super(context, themeResId);
    }

    public LoadingDialog(Context context)
    {
        super(context);
    }

    public static Builder builder(Context context)
    {
        return new Builder(context);
    }

    public static class Builder
    {
        private LoadingDialog dialog;
        private View view;

        public Builder(Context context)
        {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            dialog = new LoadingDialog(context, R.style.LoadingDialog);
            dialog.setCanceledOnTouchOutside(false);

            view = inflater.inflate(R.layout.dialog_loading, null);

            dialog.addContentView(view, new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            initView(view);
        }

        private void initView(View view)
        {
            loadingView = (MetroLoadingView) view.findViewById(R.id.loadingView);
        }

        public Builder canBeBack(boolean b)
        {
            canBeBack = b;
            return this;
        }

        public Builder setCallBack(CallBack back)
        {
            callBack = back;
            return this;
        }

        public Builder start()
        {
            loadingView.start();
            dialog.show();
            return this;
        }

        public void stop()
        {
            if (loadingView.isAnimating())
                loadingView.stop();
        }
    }


    @Override
    public void onBackPressed()
    {
        if (canBeBack)
        {
            super.onBackPressed();
            if (loadingView.isAnimating())
                loadingView.stop();
            if (callBack != null)
                callBack.onCallBack();
        }
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        if (loadingView.isAnimating())
            loadingView.stop();
    }


    public interface CallBack
    {
        void onCallBack();
    }

}
